﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace WebCrawlerHelper.Controllers
{
    public class ToolController
    {
        #region 对象JSON化

        /// <summary>
        /// 把object对象JSON化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        #endregion

        #region 还原Redis中的JSON化对象

        /// <summary>
        /// 还原Redis中的JSON化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(string json)
        {
            if (json == null)
            {
              
                json = ObjectToJson(default(T));
            }
            //json = json.Replace("\\", " ");
            return JsonConvert.DeserializeObject<T>(json);
        }

        #endregion

        public static string StringToBase64(string str)
        {
            Encoding encode = Encoding.UTF8;
            byte[] bytedata = encode.GetBytes(str);
            string strPath = Convert.ToBase64String(bytedata, 0, bytedata.Length);
            return strPath;
        }

        public static string Base64ToString(string base64)
        {
            byte[] bpath = Convert.FromBase64String(base64);
            var result = Encoding.UTF8.GetString(bpath);
            return result;
        }


        /// <summary>
        /// unicode转中文（符合js规则的） 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UnicodeDecode(string str)
        {
            string outStr = "";
            Regex reg = new Regex(@"(?i)\\u([0-9a-f]{4})");
            outStr = reg.Replace(str, delegate (Match m1)
            {
                return ((char)Convert.ToInt32(m1.Groups[1].Value, 16)).ToString();
            });
            return outStr;
        }


        /// <summary>
        /// 中英文转unicode 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UnicodeEncode(string str)
        {
            string outStr = "";
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    String ss = ((int)str[i]).ToString("x");
                    if (ss.Length != 4)
                    {
                        for (int jj = 0; jj <= 4 - ss.Length; jj++)
                        {
                            ss = "0" + ss;
                        }

                    }
                    outStr += "\\u" + ss;
                }
            }
            return outStr;
        }
    }
}
